<template>
  <el-container>
    <el-main>
      <el-form ref="warehouseForm" :model="form" :rules="rules" label-width="80px">
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">销售退货单</span>
        </div>
        <el-row type="flex" class="row-bg">
          <el-col :span="5">
            <el-form-item label="客户名称" prop="memberId">
              <el-select style="width: 100%" v-model="memberName" @focus="memberFous" value-key="id" filterable :filter-method="loadMember" placeholder="请选择客户名称"
                         @change="selectMember" >
                <el-option
                  v-for="item in memberList"
                  :key="item.id"
                  style="width: 600px;"
                  :label="item.name"
                  :value="item">
                   <div style="display: flex">
                    <span style="width: 60px;"></span>
                    <span style="float: left;width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 8px;width: 80px;margin-left: 10px">{{ item.mobile }}</span>
                    <div style="width: 200px;">
                      <span style="color: #8492a6; font-size: 8px;">{{item.address}}</span>
                    </div>
                  </div>
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">

                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="toSearchMember">搜索客户</div>
                  <div class="elOption1" @click="toAddMember">新增客户</div>
                </div>
                <div style="height: 30px"></div>
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="订单号" prop="orderSn">
              <el-select style="width:100%" v-model="orderSn" value-key="id" placeholder="请选择订单号" filterable :remote-method="loadOrder" clearable
              @change="selectOrder">
                <el-option
                style="width: 490px;"
                  v-for="(item,index) in orderInfoList"
                  :key="item.id"
                  :label="item.sn"
                  :value="item">
                  <div style="display: flex">
                    <span style="width: 120px;">{{item.sn}}</span>
                    <span style="float: left;width: 100px;overflow: hidden;text-overflow: ellipsis;">{{item.createDate | dateFormatter}}</span>
                    <div style="width: 220px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                      <span style="color: #8492a6; font-size: 8px;">{{item.address}}</span>
                    </div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售日期">
              <el-date-picker
                style="width: 100%"
                v-model="form.orderDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="所属部门">
              <el-input v-model="officeName" suffix-icon="el-icon-arrow-down" @focus="dialogShow"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="5">
            <el-form-item label="所属仓库" prop="shopId">
              <el-select style="width: 100%" v-model="shopName" value-key="id" filterable placeholder="请选择仓库"  :filter-method="remoteMethod"
                         @change="selectShop">
                <el-option
                  v-for="item in shopList"
                  :key="item.id"
                  :label="item.name"
                  :value="item">
                </el-option>

              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="配送方式">
              <el-select style="width:100%" v-model="form.shippingMethod" placeholder="请选择状态">
                <el-option label="普通快递" :value="0"></el-option>
                <el-option label="到店提货" :value="1"></el-option>
                <el-option label="同城物流" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="开票类型">
              <el-select style="width: 100%" v-model="form.taxType" placeholder="请选择状态">
                <el-option label="不开票" value="0"></el-option>
                <el-option label="增票" value="1"></el-option>
                <el-option label="普票" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="仓管员">
              <el-select style="width: 100%" v-model="operatorName" filterable placeholder="请选择"
                         @change="selectSysEmployee">
                <el-option
                  v-for="item in sysEmployeeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="10">
            <el-form-item label="收货地址" prop="address">
              <el-select style="width: 100%" v-model="form.address" value-key="id" filterable placeholder="请选择"
                         @change="selectReceiver">
                <el-option
                  v-for="item in receiverForm"
                  :key="item.id"
                  :label="item.address"
                  :value="item">
                </el-option>
                <el-option style="background-color: #f9f9f9;text-align: center;" key="*" label="底部隐藏块"
                           value="*"></el-option>
                <el-option style="background-color: #f9f9f9;text-align: center;position: absolute;bottom:0;width: 100%" key="#" label="--- 新增收货地址 ---"
                           value="#"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="收货人" prop="consignee">
              <el-input v-model="form.consignee"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="10">
            <el-form-item label="买家留言">
              <el-input v-model="form.memo"/>
            </el-form-item>
          </el-col>

        </el-row>
        <div class="product_header_name" style="">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">商品明细</span>
          <div style="display: flex;padding-top: 10px;padding-bottom: 10px">
            <el-input v-model="query.sn" placeholder="请输入货号" @change="queryClick"></el-input>
<!--            <el-button style="margin-left: 20px;margin-right: 10px" type="primary" icon="el-icon-plus"-->
<!--                       @click="moreProductClick">添加商品-->
<!--            </el-button>-->
          </div>
        </div>
        <!--商品规格-->
        <el-table
          :data="productList"
          border
          show-summary
          stripe
          style="width: 100%">
          <el-table-column
            label="排序"
            type="index"
            width="50"
          >
          </el-table-column>
          <el-table-column
            label="商品名">
            <template slot-scope="{row}">
              <div style="position: relative">
                <i class="el-icon-arrow-down" style="position: absolute;bottom: 11px;color: #CCCC;right: 8px;z-index: 99;"></i>
                <el-select style="width: 100%" v-model="row.name" filterable placeholder="请选择"  remote :remote-method="productMethod" @change="selectClick" @focus="tableClick(row)">
                  <el-option
                    v-for="(item,index) in listForm"
                    :key="index"
                    style="width:650px"
                    :label="item.name"
                    :value="index"
                  >
                    <div style="display: flex">
                      <span style="width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.sn }}</span>
                      <span style="float: left;width: 160px;overflow: hidden;text-overflow: ellipsis;margin-left: 10px">{{ item.name }}</span>
                      <div style="width: 200px;">
                        <span style="color: #8492a6; font-size: 8px;">{{item.spec1}}</span>
                      </div>
                    </div>
                  </el-option>
                  <div style="display: flex;width: 100%;position: absolute;bottom: 0">

                    <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                    <div class="elOption" @click="toAddProduct">搜索商品</div>
                    <div class="elOption1" @click="toSearchProduct">新增商品</div>
                  </div>
                  <div style="height: 30px"></div>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="规格"
            max-width="300"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.spec}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="货号/条码"
            width="150"
          >
            <template slot-scope="{row}">
              <span>{{row.sn}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="单位"
            width="50"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.unit}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            prop="quantity"
            align="center"
            width="70">
            <template slot-scope="{row}">
              <el-input @change="refreshClick" v-model="row.quantity"/>
            </template>
          </el-table-column>
          <el-table-column
            label="单价"
            width="70">
            <template slot-scope="{row}">
              <el-input @change="refreshClick" v-model="row.price"/>
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            width="70"
            align="right"
            prop="subTotal"
          >
          </el-table-column>
          <el-table-column
            label="优惠"
            width="70"
            align="right"
            prop="discount"
          >
          </el-table-column>
          <el-table-column
            label="实收"
            width="70"
            align="right"
            prop="amountPaid"
          >
          </el-table-column>
          <el-table-column
            align="center"
            width="70"
            label="操作"
          >
            <template slot-scope="{row}">
              <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                <a @click="delProduct(row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex;justify-content: flex-end">
          <!-- <el-button type="primary" style="margin-top: 20px" :loading="clicked" v-permission="['salein.in']" @click="saveAudit('warehouseForm')">保存并入库</el-button> -->
          <el-button type="success" style="margin-top: 20px" :loading="clicked" v-permission="['salein.audit']" @click="saveConfirm('warehouseForm')">保存并确认</el-button>
          <el-button  style="margin-top: 20px" :loading="clicked" @click="saveClick('warehouseForm')">保存至草稿</el-button>
        </div>

      </el-form>
      <el-dialog
        title="新增商品"
        :visible.sync="procuctVisible"
        width="68%"
        v-el-drag-dialog
        :before-close="productClose">
        <div style="height: 65vh;overflow: auto;position: relative;">
          <productAdd :type="productType" @saveProduct="saveProduct"></productAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="选择商品"
        :visible.sync="orderVisible"
        width="68%"
        v-el-drag-dialog
        :before-close="orderClose">
        <div style="position: relative;">
          <productTable ref="productList" @doubleClick="doubleClick" @addClick="addClick"></productTable>
        </div>
      </el-dialog>
      <el-dialog
        title="新增客户"
        :visible.sync="memberVisible"
        width="80%"
        v-el-drag-dialog
        append-to-body
        :before-close="memberClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <memberAdd :key="times" :memberType="memberType" @memberClick="memberClick"></memberAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="选择商品"
        :visible.sync="queryType"
        width="80%"
        v-el-drag-dialog
        append-to-body
        :before-close="queryClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <productRadio :findByList="findByList" @findByClick="findByClick"></productRadio>
        </div>
      </el-dialog>
      <el-dialog
        title="新增地址"
        :visible.sync="receiverVisible"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="receiverClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <receiverAdd :key="times" @orderReceiver="orderReceiver" pathType="0" :memberId="form.memberId"></receiverAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="双击选择客户"
        :visible.sync="memberTableVisible"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="memberTableClose">
        <div style="position: relative;">
          <member-table  @memberDouble="memberDouble" @addMemberClick="addMemberClick" @memberTableClose="memberTableClose"></member-table>
        </div>
      </el-dialog>
      <office-dialog ref="officeDialog" @confirm="dialogConfirm"/>
    </el-main>
  </el-container>
</template>
<script>
  import memberTable from '@/components/MemberTable/index'
  import {mapGetters} from 'vuex'
  import {EventBus} from '@/api/eventBus'
  import {list as shopList} from '@/api/shop'
  import {list as productList} from '@/api/product'
  import {list as orderList} from '@/api/order'
  import {list as memberList} from '@/api/member'
  import {list as sysEmployeeList} from '@/api/sysEmployee'
  import {save,saveAndConfirm,saveAndOutStock} from '@/api/warehouse'
  import utils from '../../utils/utils.js'
  import productAdd from '@/views/product/add'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import productTable from '@/components/ProductList/productList'
  import Distpicker from '@/components/Distpicker/Distpicker'
  import memberAdd from '@/views/member/add'
  import OfficeDialog from '@/components/OfficeDialog'
  import {findBySn} from "../../api/product";
  import productRadio from './components/productRadio'
  import receiverAdd from '@/views/receiver/add'
  import {list as receiverList} from '@/api/receiver'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  export default {
    directives: {elDragDialog,permission},
    name: 'salein-add',
    data() {
      return {
        shopName:'',
        name:'',
        orderSn:"",
        orderSnList:[],
        orderInfoList:[],
        shopList:[],
        times:null,
        clicked: false, // 按钮防双击
        form: {
          orderSn:"",
          orderId:'',
          shippingMethod:'',
          shopId:'',
          memberId: '',
          orderDate: new Date(),
          operatorId: '',
          officeId: '',
          areaId: 440000,
          areaName: '广东省广州市海珠区',
          address: '',
          memo: '',
          consignee: '',
          phone: '',
          subPrice: 0,
          subQuantity: 0,
          taxType: '0'
        },
        productList: [],
        query: {
          sn: ''
        },
        keyword: {
          sn: ''
        },
        listForm: [],
        tableIndex: '',
        procuctVisible: false,
        memberTableVisible:false,
        orderVisible: false,
        productType: 'order',
        chooseOrderName: '',
        district: {province: 440000, city: '广州市', area: '海珠区'},
        memberName: '',
        memberList: [],
        memberVisible: false,
        memberType: 'add',
        sysEmployeeList: [],
        operatorName: '',
        officeName: '',
        rules: {
          orderSn:[
            {required: true, message: '请输入订单号', trigger: 'blur'},
          ],
          memberId: [
            {required: true, message: '请选择客户', trigger: 'blur'},
          ],
          address: [
            {required: true, message: '请输入详细地址', trigger: 'blur'}
          ],
          shopId: [
            {required: true, message: '请选择所属仓库', trigger: 'blur'}
          ]
        },
        queryType: false,
        findByList: [],
        receiverType: false,
        memberId: '',
        receiverForm: [],
        receiverVisible: false
      }
    },
    created() {
      this.times=new Date().getSeconds()
      if (this.employee != null) {
        this.form.operatorId = this.employee.id;
        this.form.officeId = this.employee.officeId;
        this.officeName = this.employee.officeName;
        this.operatorName = this.employee.name;
      }
      this.loadlist('');
      this.loadMember('');
      this.loadSysEmployee();
      this.loadShop('')
    },
    computed: {
      ...mapGetters([
        'employee'
      ])
    },
    components: {
      productAdd, productTable, Distpicker, memberAdd, OfficeDialog, productRadio, receiverAdd,memberTable
    },
    methods: {
      remoteMethod(query){
        this.loadShop(query)
      },
      selectShop(e){
        this.form.shopId=e.id
      },
      memberDouble(data){

        this.form.memberId = data.id;
        this.memberName=data.name
        this.memberTableVisible=false
        this.loadReceiver()
      },
      toSearchMember() {
        this.memberTableVisible = true
      },
      memberTableClose(){
        this.memberName =this.name
        this.memberTableVisible=false
      },
      toAddProduct(){
        this.orderVisible = true;

      },
      toSearchProduct(){
        this.procuctVisible = true;
      },
      toAddMember() {

        this.memberVisible = true;
        this.times = new Date().getSeconds()
      },
      productMethod(query){
        this.loadlist(query)
      },
      loadShop(query) {
        var _this = this
        let params = new URLSearchParams();
        params.append('name',query)
        shopList(params).then(response => {
          _this.shopList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      //订单查询
      loadOrder(query) {
        var _this = this
        let params = new URLSearchParams();
        params.append('orderSn',query)
        orderList(params).then(response => {
          console.info("订单信息")
          console.info(response)
          _this.orderSnList = []
          _this.orderInfoList = []
          if(response.data.data.length > 0){
            response.data.data.map(item=>{
              _this.orderSnList.push(item.sn)
              _this.orderInfoList.push(item)
            })
          }
          // _this.shopList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      //订单查询
      loadOrderByMemeberId(id) {
        var _this = this
        let params = new URLSearchParams();
        params.append('memberId',id)
        orderList(params).then(response => {
          console.info("订单信息")
          console.info(response)
          _this.orderSnList = []
          _this.orderInfoList = []
          if(response.data.data.length > 0){
            response.data.data.map(item=>{
              _this.orderSnList.push(item.sn)
              _this.orderInfoList.push(item)
            })
          }
          // _this.shopList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      selectOrder(query){
        var _this = this
        _this.memberName = ""
        _this.form.address = ""
        _this.form.phone = ""
        _this.form.consignee = ""
        _this.productList = []
        if(_this.orderInfoList.length > 0){
          _this.orderInfoList.map(item =>{
            if(item.sn == query.sn){
              _this.form.orderSn = query.sn
              _this.form.orderId=query.id
              _this.form.shippingMethod=query.shippingMethod
              _this.form.memberId = item.memberId;
              _this.memberName = item.memberName
              _this.form.address = item.address
              _this.form.phone = item.phone
              _this.form.consignee = item.consignee
              if(item.itemList.length > 0){
                item.itemList.map(item1 => {
                  if(item1.availableReturnQuantity > 0){
                    item1.quantity=item1.availableReturnQuantity
                    _this.productList.push(item1)
                  }
                })
              }
            }
          })
          _this.addProduct()
        }
      },
      //删除商品列表
      delProduct(row) {
        var index = this.productList.indexOf(row)
        if (index !== -1) {
          this.productList.splice(index, 1)
        }
        this.addProduct()
      },
      memberFous(){
        this.name=this.memberName
      },
      addMemberClick(val){
        val.forEach(item=>{
          this.form.memberId = item.id;
          this.memberName=item.name
        })
        this.loadReceiver()
      },
      //新增商品
      addProduct() {
        var _this = this
        if (_this.productList.length == 0) {
          _this.productList.push({
            productId: '',
            name: '',
            sn: '',
            price: 0,
            orders: '',
            quantity: 0,
            subTotal: 0,
            amountPaid: 0,
            spec: '',
            discount: 0,
            cost: 0,
            unit: ''
          })
        } else {
          if (_this.productList[_this.productList.length - 1].productId!= '') {
            _this.productList.push({
              productId: '',
              name: '',
              sn: '',
              price: 0,
              orders: '',
              quantity: 0,
              subTotal: 0,
              amountPaid: 0,
              spec: '',
              discount: 0,
              cost: 0,
              unit: ''
            })
          }
        }
      },
      //商品总数据
      loadlist(query) {
        var _this = this
        let params = new URLSearchParams();
        params.append('sn', _this.keyword.sn)
        params.append('keyword',query)
        productList(params).then(response => {
          console.log(response);
          _this.listForm = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      //更多商品弹出
      moreProductClick() {
        var _this = this;
        _this.orderVisible = true;
      },
      doubleClick(data) {
        var goodsDetails = {
          productId: data.id,
          name: data.name,
          sn: data.sn,
          price: data.price,
          orders: data.orders,
          subTotal: data.price,
          cost:data.cost,
          amountPaid: 0,
          discount: 0,
          quantity: 1,
          spec: data.spec1 + data.spec2,
          unit:data.unit,
        };
        this.productList.push(goodsDetails)
        this.procuctFilter();
        this.addProduct()
        // this.calculateClick()
      },
      addClick(data) {
        var _this = this
        console.log(data)
        data.forEach(function (item) {
          var goodsDetails = {
            productId: item.id,
            name: item.name,
            sn: item.sn,
            price: item.price,
            orders: item.orders,
            subTotal: item.price,
            cost:item.cost,
            amountPaid: 0,
            discount: 0,
            quantity: 1,
            spec: item.spec1 + item.spec2,
            unit:item.unit
          };
          _this.productList.push(goodsDetails)
        });
        this.procuctFilter();
        this.orderVisible = false;
        this.addProduct()
        // this.calculateClick()
      },
      orderClose() {
        this.orderVisible = false;
        if ( this.productList.length>0&&this.chooseOrderName!=''){
          this.productList[this.tableIndex].name = this.chooseOrderName
        }
        this.$refs.productList.cancelClick();
      },
      //商品表下拉选择
      selectClick(index) {
        var _this = this
        if (index == '#') {
          _this.procuctVisible = true;
        } else {
          var goodsDetails = {
            productId: _this.listForm[index].id,
            name: _this.listForm[index].name,
            sn: _this.listForm[index].sn,
            cost: _this.listForm[index].cost,
            price: _this.listForm[index].price,
            orders: _this.listForm[index].orders,
            subTotal: _this.listForm[index].price,
            unit: _this.listForm[index].unit,
            spec: _this.listForm[index].spec1 + _this.listForm[index].spec2,
            amountPaid: 0,
            discount: 0,
            quantity: 1
          };
          _this.productList[_this.tableIndex] = goodsDetails
        }
        this.procuctFilter();
        this.addProduct()
      },
      //获取当前点击商品表行
      tableClick(data) {
        this.tableIndex = this.productList.indexOf(data);
        this.chooseOrderName = this.productList[this.tableIndex].name
      },
      //新增商品弹窗
      productClose() {
        this.procuctVisible = false;
        this.productList[this.tableIndex].name = this.chooseOrderName
      },
      saveProduct(data) {
        this.listForm.splice(0, 0, data);
        this.productList[this.tableIndex] = data;
        this.procuctVisible = false;
      },
      //商品过滤
      procuctFilter() {
        let newfood = [];
        var temp = {};
        for (var i in this.productList) {
          if (this.productList[i].productId != '') {
            var key = this.productList[i].productId;
            if (temp[key]) {
              temp[key].productId = temp[key].productId;
              temp[key].quantity = temp[key].quantity + this.productList[i].quantity;
              temp[key].subTotal = parseInt(this.productList[i].price) * parseInt(temp[key].quantity);
              temp[key].amountPaid = temp[key].subTotal
            } else {
              temp[key] = {};
              temp[key].productId = this.productList[i].productId;
              temp[key].quantity = this.productList[i].quantity;
              temp[key].subTotal = parseInt(this.productList[i].price) * parseInt(temp[key].quantity);
              temp[key].amountPaid = temp[key].subTotal
            }
            temp[key].name = this.productList[i].name;
            temp[key].sn = this.productList[i].sn;
            temp[key].price = this.productList[i].price;
            temp[key].cost = this.productList[i].cost;
            temp[key].orders = this.productList[i].orders;
            temp[key].discount = this.productList[i].discount;
            temp[key].spec = this.productList[i].spec;
            temp[key].unit = this.productList[i].unit
          }
        }
        for (var k in temp) {
          newfood.push(temp[k])
        }
        this.productList = newfood
        console.log(newfood)
      },
      saveConfirm(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          console.log(valid)
          if (valid) { // 校验表单
            _this.clicked = true
            let itemList = [];
            if (_this.productList[_this.productList.length-1].productId==''){
              _this.productList.splice(_this.productList.length-1,1)
            }
            _this.productList.forEach(function (item) {
              var goodsDetails = {
                productId: item.productId,
                name: item.name,
                sn: item.sn,
                unit:item.unite,
                discount:0,
                price: item.price,
                quantity: item.quantity,
                spec: item.spec,
                cost: item.cost,
              };
              itemList.push(goodsDetails)
            });
            _this.form.subPrice = _this.productList.reduce(function (totle, item) {
              return totle + (item.quantity * item.price)
            }, 0)
            _this.form.subQuantity = _this.productList.reduce(function (totle, item) {
              return totle + item.quantity
            }, 0)
            let formData = {
              shippingMethod:_this.form.shippingMethod,
              memberId: _this.form.memberId,
              orderDate: _this.form.orderDate,
              orderSn:_this.form.orderSn,
              orderId:_this.form.orderId,
              operatorId: _this.form.operatorId,
              officeId: _this.form.officeId,
              areaName: _this.form.areaName,
              address: _this.form.address,
              areaId: _this.form.areaId,
              memo: _this.form.memo,
              phone: _this.form.phone,
              consignee: _this.form.consignee,
              warehouseType: 5,
              subPrice: _this.form.subPrice,
              subQuantity: _this.form.subQuantity,
              shopId: _this.form.shopId,
              supplierId: 1,
              taxType: _this.form.taxType,
              itemList: itemList,
            };
            console.info("表单数据---")
            console.info(formData)
            saveAndConfirm(formData).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('salein-add', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/salein/list'
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },
      saveAudit(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          console.log(valid)
          if (valid) { // 校验表单
            _this.clicked = true
            let itemList = [];
            if (_this.productList[_this.productList.length-1].productId==''){
              _this.productList.splice(_this.productList.length-1,1)
            }
            _this.productList.forEach(function (item) {
              var goodsDetails = {
                productId: item.productId,
                name: item.name,
                sn: item.sn,
                unit:item.unite,
                discount:0,
                price: item.price,
                quantity: item.quantity,
                spec: item.spec,
                cost: item.cost,
              };
              itemList.push(goodsDetails)
            });
            _this.form.subPrice = _this.productList.reduce(function (totle, item) {
              return totle + (item.quantity * item.price)
            }, 0)
            _this.form.subQuantity = _this.productList.reduce(function (totle, item) {
              return totle + item.quantity
            }, 0)
            let formData = {
              shippingMethod:_this.form.shippingMethod,
              memberId: _this.form.memberId,
              orderDate: _this.form.orderDate,
              orderSn:_this.form.orderSn,
              orderId:_this.form.orderId,
              operatorId: _this.form.operatorId,
              officeId: _this.form.officeId,
              areaName: _this.form.areaName,
              address: _this.form.address,
              areaId: _this.form.areaId,
              memo: _this.form.memo,
              phone: _this.form.phone,
              consignee: _this.form.consignee,
              warehouseType: 5,
              subPrice: _this.form.subPrice,
              subQuantity: _this.form.subQuantity,
              shopId: _this.form.shopId,
              supplierId: 1,
              taxType: _this.form.taxType,
              itemList: itemList,
            };
            saveAndOutStock(formData).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('salein-add', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/salein/list'
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },
      //订单保存
      saveClick(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          console.log(valid)
          if (valid) { // 校验表单
            _this.clicked = true
            let itemList = [];
            if (_this.productList[_this.productList.length-1].productId==''){
              _this.productList.splice(_this.productList.length-1,1)
            }
            _this.productList.forEach(function (item) {
              var goodsDetails = {
                productId: item.productId,
                name: item.name,
                sn: item.sn,
                unit:item.unite,
                discount:0,
                price: item.price,
                quantity: item.quantity,
                spec: item.spec,
                cost: item.cost,
              };
              itemList.push(goodsDetails)
            });
            _this.form.subPrice = _this.productList.reduce(function (totle, item) {
              return totle + (item.quantity * item.price)
            }, 0)
            _this.form.subQuantity = _this.productList.reduce(function (totle, item) {
              return totle + item.quantity
            }, 0)
            let formData = {
              shippingMethod:_this.form.shippingMethod,
              memberId: _this.form.memberId,
              orderDate: _this.form.orderDate,
              orderSn:_this.form.orderSn,
              orderId:_this.form.orderId,
              operatorId: _this.form.operatorId,
              officeId: _this.form.officeId,
              areaName: _this.form.areaName,
              address: _this.form.address,
              areaId: _this.form.areaId,
              memo: _this.form.memo,
              phone: _this.form.phone,
              consignee: _this.form.consignee,
              warehouseType: 5,
              subPrice: _this.form.subPrice,
              subQuantity: _this.form.subQuantity,
              shopId: _this.form.shopId,
              supplierId: 1,
              taxType: _this.form.taxType,
              itemList: itemList,
            };
            save(formData).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('salein-add', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/salein/list'
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },
      //地址选择
      onSelected(val) {
        if (!utils.isNull(val.area) && !utils.isNull(val.area.code)) {
          this.form.areaId = val.area.code;
          this.form.areaName = val.area.value;
        }
      },
      //会员选择
      loadMember(query) {
        var _this = this
        let params = new URLSearchParams();
        params.append('keyword',query)
        memberList(params).then(response => {
          console.log(response);
          _this.memberList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      selectMember(data) {
        console.log(data)
        var _this = this;
        if (data.id!=this.form.memberId){
          this.productList=[]
        }
        _this.orderSn = '';
        _this.form.address = '';
        _this.form.areaName = '';
        _this.form.areaId = '';
        _this.form.consignee = '';
        _this.form.phone = '';
        _this.receiverForm = [];
        if (data == '#') {
          this.times=new Date().getSeconds()
          _this.memberVisible = true;
        }  else if (data=='/'){
          _this.memberName=''
          _this.memberTableVisible=true
        }else {
          _this.memberName=data.name
          _this.form.memberId = data.id;
          _this.loadOrderByMemeberId(data.id)
          _this.loadReceiver()
          // _this.loadReceiver();
          // if (!utils.isNull(data.areaId)) {
          //   _this.form.address = data.address
          //   _this.form.areaName = data.areaName
          //   _this.form.areaId = data.areaId;
          // }
        }
      },
      memberClose() {
        this.memberVisible = false;
        this.memberName = '';
      },
      memberClick(data) {
        var _this = this;
        _this.memberName = data.name;
        _this.form.memberId = data.id;
        _this.memberVisible = false;
      },
      //  业务员
      loadSysEmployee() {
        var _this = this
        let params = new URLSearchParams();
        sysEmployeeList(params).then(response => {
          console.log(response);
          _this.sysEmployeeList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      selectSysEmployee(data) {
        this.form.operatorId = data
      },
      //  销售公司
      dialogShow() {
        console.log('点击了')
        this.$refs.officeDialog.show()
      },
      dialogConfirm(val) {
        this.form.officeId = val.id;
        this.officeName = val.name
      },
      receiverClick(data) {
        console.log(data)
        var _this = this
        _this.form.address = data.address;
        _this.form.areaName = data.areaName;
        _this.form.areaId = data.areaId;
        _this.district = utils.decodeArea(data.areaId.toString());
        _this.receiverType = false
      },
      //刷新商品合计
      refreshClick() {
        this.procuctFilter()
      },
      queryClick() {
        var _this = this
        let params = new URLSearchParams();
        params.append('sn', _this.query.sn);
        findBySn(params).then(response => {
          console.log(response)
          if (response.data.products.length == 1) {
            var goodsDetails = {
              productId: response.data.products[0].id,
              name: response.data.products[0].name,
              sn: response.data.products[0].sn,
              cost: response.data.products[0].cost,
              price: response.data.products[0].price,
              orders: response.data.products[0].orders,
              subTotal: response.data.products[0].price,
              spec: response.data.products[0].spec1 + response.data.products[0].spec2,
              amountPaid: 0,
              discount: 0,
              quantity: 1,
              unit: response.data.products[0].unit
            };
            _this.productList.push(goodsDetails)
            _this.procuctFilter()
          } else if (response.data.products.length > 1) {
            _this.findByList = response.data.products
            _this.queryType = true
          }
          _this.addProduct()
        }).catch(error => {
          console.log('error!!')
        });
      },
      queryClose() {
        this.queryType = false
      },
      findByClick(data) {
        var _this = this
        console.log(data)
        data.forEach(function (item) {
          _this.productList.push(item)
        });
        this.queryType = false
        this.procuctFilter();
      },

      loadReceiver() {
        var _this = this
        let params = new URLSearchParams();
        params.append('pageNum', 1);
        params.append('pageSize', 100);
        params.append('memberId', _this.form.memberId);
        receiverList(params).then(response => {
          console.log(response)
          _this.receiverForm = response.data.data
          _this.form.address = response.data.data[0].address
          _this.form.areaName = response.data.data[0].areaName
          _this.form.areaId = response.data.data[0].areaId;
          _this.form.consignee = response.data.data[0].consignee;
          _this.form.phone = response.data.data[0].phone
        }).catch(error => {
          console.log('error!!')
        });
      },
      selectReceiver(data) {
        console.log(data)
        var _this = this
        if (utils.isNull(_this.form.memberId)) {
          _this.$message({
            message: '请先选择客户',
            type: 'warning'
          });
          this.form.address = ''
          return;
        }
        if (data == '#') {
          this.times=new Date().getSeconds()
          _this.receiverVisible = true;
          this.form.address = ''
        } else {
          _this.form.address = data.address
          _this.form.areaName = data.areaName
          _this.form.areaId = data.areaId;
          _this.form.consignee = data.consignee;
          _this.form.phone = data.phone
        }
      },
      receiverClose() {
        this.receiverVisible = false;
      },
      orderReceiver(data) {
        var _this = this
        _this.receiverForm.push(data.data)
        _this.form.address = data.data.address
        _this.form.areaName = data.data.areaName
        _this.form.areaId = data.data.areaId;
        _this.form.consignee = data.data.consignee;
        _this.form.phone = data.data.phone;
        _this.receiverClose()
      },
    }
  }
</script>

<style scoped>
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #CCCCCC;
  }

  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    padding-right: 20px;
    justify-content: space-between;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
  .elOption1{
    background-color: #409EFF;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;

    width: 25%;
    height: 40px
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;

    width: 25%;
    height: 40px
  }
</style>
